<template>
  <div>
    <a-card :bordered="false">

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleCreate">新增类别</a-button>
      </div>

      <a-table rowKey="id" ref="table" :columns="columns" :data-source="data">
        <span slot="action" slot-scope="text, record">
          <template>
            <a v-if="showCreateChild(record)" @click="handleCreateChild(record)">
              新增子类别
              <a-divider type="vertical"/>
            </a>

            <a @click="handleEdit(record)">编辑</a>

            <a-popconfirm placement="top" @confirm="confirmDelete(record)">
              <template slot="title">
                确定要删除吗?
              </template>
              <a v-if="canDelete(record)">
                <a-divider type="vertical"/>
                删除
              </a>
            </a-popconfirm>
          </template>
        </span>
      </a-table>
    </a-card>

    <a-modal
      :title="formTitle"
      :visible="formVisibleStatus"
      :confirm-loading="formConfirmLoading"
      @ok="formHandleOk"
      @cancel="formHandleDone"
    >
      <a-form ref="form" :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="类别名称">
          <a-input
            v-decorator="['name', { rules: [{ required: true, message: '请输入类别名称' }] }]"
          />
        </a-form-item>

        <a-form-item label="排序">
          <a-input-number :min="1" :max="255" v-decorator="['sort_id']"/>
        </a-form-item>
      </a-form>

    </a-modal>
  </div>
</template>

<script>
  import { deleteCommodityCategory, getCommodityCategoryList, saveCommodityCategory } from '@/api/commodity'
  import Vue from 'vue'

  export default {
    name: 'List',
    data () {
      return {
        data: [],
        columns: [
          {
            title: '类别名称',
            dataIndex: 'name'
          },
          {
            // TODO 还没有把子节点的加起来
            title: '商品数量',
            dataIndex: 'commodity_quantity'
          },
          {
            title: '排序',
            dataIndex: 'sort_id',
            customRender: (index, item) => {
              const sortId = item.parent_id === null ? item.sort_id : (item.parent_sort_id + '-' + item.sort_id)
              if (item.hasOwnProperty('children')) {
                // 加上父节点的排序号
                item.children.forEach(record => {
                  record.parent_sort_id = sortId
                })

                // 如果没有子节点了 删除 children, 来隐藏列表的 展开
                if (item.children.length === 0) {
                  Vue.delete(item, 'children')
                }
              }

              return sortId
            }
          },
          {
            title: '操作',
            width: '20%',
            scopedSlots: { customRender: 'action' }
          }
        ],

        form: this.$form.createForm(this),
        formTitle: '',
        formVisibleStatus: false,
        formConfirmLoading: false,
        formParentId: 0,
        formCurrentId: 0,
        formCurrentRecord: null
      }
    },
    created () {
      this.getData()
    },
    methods: {
      confirmDelete (record) {
        deleteCommodityCategory(record.id).then(res => {
          this.getData().then(_ => {
            this.$message.success('删除成功!')
          })
        })
      },
      canDelete (record) {
        const hasNotChildren = !record.hasOwnProperty('children') || record.children.length === 0
        const hasNotCommodify = record.commodity_quantity === 0

        return hasNotChildren && hasNotCommodify
      },
      showCreateChild (record) {
        return record.parent_id === null
      },
      handleCreate () {
        this.formTitle = '新增一级类别'
        this.formVisibleStatus = true
      },
      handleCreateChild (record) {
        this.formTitle = '新增子类别'
        this.formVisibleStatus = true
        this.formParentId = record.id
      },
      formHandleOk () {
        this.form.validateFields((err, values) => {
          if (!err) {
            if (this.formParentId !== 0) {
              values.parent_id = this.formParentId
            }
            if (this.formCurrentId !== 0) {
              values.id = this.formCurrentId
            }
            saveCommodityCategory(values).then(res => {

            }).finally(_ => {
              this.getData()
              this.formHandleDone()
            })
          } else {
            this.formConfirmLoading = false
          }
        })
      },
      formHandleDone () {
        this.formVisibleStatus = false
        this.formParentId = 0
        this.formCurrentId = 0
        this.form.resetFields()
      },
      handleEdit (record) {
        this.formTitle = '编辑类别'
        this.formVisibleStatus = true
        this.formCurrentId = record.id

        this.$nextTick(_ => {
          this.form.setFieldsValue({
            name: record.name,
            sort_id: record.sort_id
          })
        })
      },
      getData () {
        return new Promise((resolve, reject) => {
          getCommodityCategoryList().then(res => {
            this.data = res
            return resolve()
          })
        })
      }
    }
  }
</script>

<style scoped>

</style>
